﻿using System.Net;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ZXing;
using ZXing.Common;
using Traceability.Register.Application.Commonds.TraceabilityManagementCommonds;
using Traceability.Register.ErrorCode.Result;
using System.IO;
using System;
using System.Linq;
using iTextSharp.text.pdf.qrcode;

namespace Traceability.Register.Read.API.Controllers
{
    /// <summary>
    /// 上传图片控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UpdatelocadsController : ControllerBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UpdatelocadsController> logger;
        /// <summary>
        /// 中介者
        /// </summary>
        private readonly IMediator mediator;
        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="mediator">中介者</param>
        public UpdatelocadsController(ILogger<UpdatelocadsController> logger, IMediator mediator)
        {
            this.logger = logger;
            this.mediator = mediator;
        }


        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file">图片类型</param>
        /// <returns>返回地址</returns>
        [HttpPost]
        public IActionResult Uplocads(IFormFile file)
        {
            try
            {
                var name = DateTime.Now.ToString().Replace("T", "").Replace(":", "");
                var invalidChars = Path.GetInvalidFileNameChars().Concat(Path.GetInvalidPathChars()).Distinct().ToArray();
                var fileName = new string(file.FileName.Select(x => invalidChars.Contains(x) ? '_' : x).ToArray());
                var filePath = Path.Combine("wwwroot/uploads/", name + fileName);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                var fileUrl = Request.Scheme + "://" + Request.Host + "/uploads/" + name + fileName;

                return Ok(new { message = "File uploaded successfully!", fileUrl });
            }
            catch (Exception ex)
            {
                logger.LogError("上传失败" + ex.Message);
                throw;
            }
        }
       

       //生成二维码
       [HttpGet]
       public FileResult GenerateQRCode(string content)
        {
            using (var ms = new MemoryStream())
            {
                var qrCodeWriter = new QRCodeWriter();
                var qrCode = qrCodeWriter.Encode(content,  300, 300);
                var barcodeWriter = new BarcodeWriterPixelData();
                return File(ms.ToArray(), "image/png");
            }           
        }
    }
}
